package com.example.farmrental.controller;

import com.example.farmrental.dto.ApiResponse;
import com.example.farmrental.dto.PageResponse;
import com.example.farmrental.entity.UserEntity;
import com.example.farmrental.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/** 用户管理 CRUD 接口（兼容 Java 8） */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    /** 分页列表（支持关键词 name/username 模糊匹配） */
    @GetMapping
    public ResponseEntity<ApiResponse<PageResponse<UserEntity>>> list(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "9") int size,
            @RequestParam(required = false) String keyword) {
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "id"));
            if (keyword != null && !keyword.isEmpty()) {
                // 内存过滤（数据量较小场景），如需数据库模糊可改为自定义查询
                List<UserEntity> all = userRepository.findAll(Sort.by(Sort.Direction.DESC, "id"));
                List<UserEntity> filtered = new ArrayList<UserEntity>();
                for (UserEntity u : all) {
                    String n = u.getName() == null ? "" : u.getName();
                    String un = u.getUsername() == null ? "" : u.getUsername();
                    if (n.contains(keyword) || un.contains(keyword)) {
                        filtered.add(u);
                    }
                }
                int from = Math.min(page * size, filtered.size());
                int to = Math.min(from + size, filtered.size());
                List<UserEntity> slice = filtered.subList(from, to);
                PageResponse<UserEntity> resp = new PageResponse<UserEntity>(slice, filtered.size(), page, size);
                return ResponseEntity.ok(ApiResponse.success("获取用户列表成功", resp));
            } else {
                Page<UserEntity> p = userRepository.findAll(pageable);
                PageResponse<UserEntity> resp = new PageResponse<UserEntity>(p.getContent(), p.getTotalElements(), page, size);
                return ResponseEntity.ok(ApiResponse.success("获取用户列表成功", resp));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取用户列表失败: " + e.getMessage()));
        }
    }

    /** 新增 */
    @PostMapping
    public ResponseEntity<ApiResponse<UserEntity>> create(@RequestBody UserEntity u) {
        try {
            if (u.getStatus() == null) u.setStatus(1);
            return ResponseEntity.ok(ApiResponse.success("新增用户成功", userRepository.save(u)));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("新增用户失败: " + e.getMessage()));
        }
    }

    /** 修改 */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<UserEntity>> update(@PathVariable Long id, @RequestBody UserEntity payload) {
        Optional<UserEntity> opt = userRepository.findById(id);
        if (!opt.isPresent()) return ResponseEntity.ok(ApiResponse.error("用户不存在", 404));
        UserEntity u = opt.get();
        u.setName(payload.getName());
        u.setUsername(payload.getUsername());
        u.setPhone(payload.getPhone());
        if (payload.getPassword() != null && !payload.getPassword().isEmpty()) u.setPassword(payload.getPassword());
        u.setStatus(payload.getStatus());
        return ResponseEntity.ok(ApiResponse.success("修改用户成功", userRepository.save(u)));
    }

    /** 删除 */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> delete(@PathVariable Long id) {
        try {
            userRepository.deleteById(id);
            return ResponseEntity.ok(ApiResponse.success("删除用户成功"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除用户失败: " + e.getMessage()));
        }
    }

    /** 启用/停用 */
    @PatchMapping("/{id}/status")
    public ResponseEntity<ApiResponse<UserEntity>> changeStatus(@PathVariable Long id, @RequestBody Map<String, Integer> body) {
        Optional<UserEntity> opt = userRepository.findById(id);
        if (!opt.isPresent()) return ResponseEntity.ok(ApiResponse.error("用户不存在", 404));
        Integer s = body.get("status");
        if (s == null) return ResponseEntity.ok(ApiResponse.error("请提供状态参数", 400));
        UserEntity u = opt.get();
        u.setStatus(s);
        return ResponseEntity.ok(ApiResponse.success("更新状态成功", userRepository.save(u)));
    }
}
